package com.vshop.platform.system.crud.dao;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vshop.platform.system.domain.entity.SysMenu;
import com.vshop.platform.system.crud.mapper.SysMenuMapper;
import com.vshop.platform.system.domain.param.SysMenuParam;
import org.springframework.stereotype.Repository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.vshop.platform.system.domain.entity.table.SysMenuTableDef.SysMenuTable;
import static com.vshop.platform.system.domain.entity.table.SysRoleMenuTableDef.SysRoleMenuTable;
import static com.vshop.platform.system.domain.entity.table.SysRoleTableDef.SysRoleTable;
import static com.vshop.platform.system.domain.entity.table.SysUserRoleTableDef.SysUserRoleTable;


/**
 * 菜单权限表  服务层实现。
 *
 * @author vshop
 * @since 2024-11-18
 */
@RequiredArgsConstructor
@Slf4j
@Repository
public class SysMenuDao extends ServiceImpl<SysMenuMapper, SysMenu> {
    /**
     * 管理员菜单查询条件
     */
    public QueryWrapper buildAdminQueryWrapper() {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.from(SysMenuTable)
//                .and(SysMenuTable.Status.eq(Constants.StatusNormal))
                .orderBy(SysMenuTable.ParentId.asc())
                .orderBy(SysMenuTable.SortNum.asc());
        return queryWrapper;
    }

    /**
     * 用户菜单查询条件
     */
    public QueryWrapper buildUserQueryWrapper(Long userId) {
        QueryWrapper queryWrapper = QueryWrapper.create();
         /*select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component, m.`query`, m.visible, m.status, ifnull(m.perms,'') as perms, m.is_frame, m.is_cache, m.menu_type, m.icon, m.order_num, m.create_time
            from sys_menu m
            left join sys_role_menu rm on m.menu_id = rm.menu_id
            left join sys_user_role ur on rm.role_id = ur.role_id
            left join sys_role ro on ur.role_id = ro.role_id
            where ur.user_id = #{params.userId}
            <if test="menuName != null and menuName != ''">
                    AND m.menu_name like concat('%', #{menuName}, '%')
            </if>
            <if test="visible != null and visible != ''">
                    AND m.visible = #{visible}
            </if>
            <if test="status != null and status != ''">
                    AND m.status = #{status}
            </if>
                order by m.parent_id, m.order_num*/
        queryWrapper = queryWrapper
                .select(QueryMethods.distinct(SysMenuTable.MenuId, SysMenuTable.ParentId,
                        SysMenuTable.MenuName, SysMenuTable.Path, SysMenuTable.Component,
                        SysMenuTable.QueryParam, SysMenuTable.Visible, SysMenuTable.Status,
                        SysMenuTable.Perms, SysMenuTable.IsFrame, SysMenuTable.IsCache,
                        SysMenuTable.MenuType, SysMenuTable.Icon, SysMenuTable.SortNum,
                        SysMenuTable.CreateTime))
                .from(SysMenuTable)
                .leftJoin(SysRoleMenuTable).on(SysMenuTable.MenuId.eq(SysRoleMenuTable.MenuId))
                .leftJoin(SysUserRoleTable).on(SysRoleMenuTable.RoleId.eq(SysUserRoleTable.RoleId))
                .leftJoin(SysRoleTable).on(SysRoleTable.RoleId.eq(SysUserRoleTable.RoleId))
                .where(SysUserRoleTable.UserId.eq(userId));
//            if (StringUtils.isNotEmpty(menuBo.getMenuName())) {
//                queryWrapper.and(SysMenuTable.MENU_NAME.like(menuBo.getMenuName()));
//            }
//            if (StringUtils.isNotEmpty(menuBo.getVisible())) {
//                queryWrapper.and(SysMenuTable.VISIBLE.eq(menuBo.getVisible()));
//            }
//            if (StringUtils.isNotEmpty(menuBo.getStatus())) {
//                queryWrapper.and(SysMenuTable.STATUS.eq(menuBo.getStatus()));
//            }
        queryWrapper.orderBy(SysMenuTable.ParentId.asc())
                .orderBy(SysMenuTable.SortNum.asc());
        return queryWrapper;
    }


    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    public Set<String> listMenuPermsByUserId(Long userId) {
        /*select distinct m.perms
        from sys_menu m
        left join sys_role_menu rm on m.menu_id = rm.menu_id
        left join sys_user_role ur on rm.role_id = ur.role_id
        left join sys_role r on r.role_id = ur.role_id
        where m.status = '0' and r.status = '0' and ur.user_id = #{userId}*/
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(QueryMethods.distinct(SysMenuTable.Perms))
                .from(SysMenuTable)
                .leftJoin(SysRoleMenuTable).on(SysRoleMenuTable.MenuId.eq(SysMenuTable.MenuId))
                .leftJoin(SysUserRoleTable).on(SysUserRoleTable.RoleId.eq(SysRoleMenuTable.RoleId))
                .leftJoin(SysRoleTable).on(SysRoleTable.RoleId.eq(SysUserRoleTable.RoleId))
                .where(SysMenuTable.Status.eq("0"))
                .and(SysRoleTable.Status.eq("0"))
                .and(SysUserRoleTable.UserId.eq(userId));

        List<String> perms = this.listAs(queryWrapper, String.class);

        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (ObjectUtil.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 校验菜单名称是否唯一
     */
    public boolean checkExistMenuName(SysMenuParam param) {
        long menuId = ObjectUtil.isNull(param.getMenuId()) ? -1L : param.getMenuId();
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.from(SysMenuTable)
                .where(SysMenuTable.MenuName.eq(param.getMenuName()))
                .and(SysMenuTable.ParentId.eq(param.getParentId()))
                .and(SysMenuTable.MenuId.ne(menuId));
        return this.exists(queryWrapper);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    public boolean hasChildByMenuId(Long menuId) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.from(SysMenuTable)
                .and(SysMenuTable.ParentId.eq(menuId));
        return this.exists(queryWrapper);
    }

    public boolean checkMenuHasRoleByMenuId(Long menuId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(QueryMethods.count(SysRoleMenuTable.RoleId))
                .from(SysRoleMenuTable)
                .where(SysRoleMenuTable.MenuId.eq(menuId));
        return this.count(queryWrapper) > 0;
    }

}
